import jwt from "jsonwebtoken";
import { promisify } from "node:util";
import configDefault from "../config/config.default.js";
const sign = promisify(jwt.sign);
const verify = promisify(jwt.verify);
const { uuid: SECRET } = configDefault;
export const createToken = async (userInfo) => {
  return await sign({ userInfo }, SECRET, {
    expiresIn: 60 * 60 * 24,
  });
};

// 鉴权中间件
export const authMiddleware = async (req, res, next) => {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token)
    res.status(401).json({
      code: 401,
      error: "请传入token",
    });
  try {
    const decoded = await verify(token, SECRET);
    req.user = decoded.userInfo;
    next();
  } catch (error) {
    res.status(401).json({ code: 401, error: "未授权" });
  }
};

